﻿Imports System.Net.Sockets
Imports System.Net
Imports System.Threading
Imports System.Text
Imports System.IO
Public Class TextHandling
    Public Shared WhisperedLast As String
    Private Shared LogMessageQueue As New Queue
    Public Shared sw As StreamWriter
    Public Shared Function IsStandard(ByVal Tested As Object)
        Dim Numbers() As String = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "A", "S", "D", "F", "G", "H", "J", "K", "L", "Z", "X", "C", "V", "B", "N", "M", "]", "[", ",", ".", Chr(34)}
        Dim X As Integer = 0
        While 41 > X
            If Tested = Numbers(X) Then
                Return True
            End If
            X = X + 1
        End While
        Return False
    End Function

    Public Shared Sub UpdateChannelLabel()
        MainForm.ChannelLabel.Text = Settings.CurrentChannel & " (" & MainForm.UserBox.Items.Count() & ")"
    End Sub

    Public Shared Sub SelectType(ByVal Message2 As String)
        Try
            Dim Type As String
            Dim Message As String
            If IsStandard(Message2.Substring(0, 1)) Then
                Message = Message2
                Type = Message2.Substring(0, 4)
            Else
                Message = Message2.Remove(0, 1)
                Type = Message.Substring(0, 4)
            End If
            Select Case Type
                Case 1001
                    'Users Already In Channel
                    Dim UserNameTemp As String() = Message.Split(" ")
                    Dim UserName As String = UserNameTemp(2)

                    Dim UserNameLVI As ListViewItem = MainForm.UserBox.FindItemWithText(UserName)

                    If MainForm.UserBox.Items.IndexOf(UserNameLVI) = -1 Then
                        MainForm.AddUser(UserName, UserNameTemp(3), UserNameTemp(4).Substring(1, UserNameTemp(4).Length - 2))
                    End If
                    UpdateChannelLabel()
                Case 1002
                    'User Entering the Channel
                    Dim UserNameTemp As String() = Message.Split(" ")
                    Dim UserName As String = UserNameTemp(2)

                    QueueMessage("", UserName + " has joined the channel.", "System")

                    Dim UserNameLVI As ListViewItem = MainForm.UserBox.FindItemWithText(UserName)

                    If MainForm.UserBox.Items.IndexOf(UserNameLVI) = -1 Then
                        MainForm.AddUser(UserName, UserNameTemp(3), UserNameTemp(4).Substring(1, UserNameTemp(4).Length - 2))
                    End If
                    UpdateChannelLabel()
                Case 1003
                    'User Leaving the Channel
                    Dim UserNameTemp As String() = Message.Split(" ")
                    Dim UserName As String = UserNameTemp(2)

                    QueueMessage("", UserName + " has left the channel.", "System")
                    Dim UserNameLVI As ListViewItem = MainForm.UserBox.FindItemWithText(UserName)
                    Dim UserNameIndex As Integer = MainForm.UserBox.Items.IndexOf(UserNameLVI)
                    If MainForm.UserBox.Items.IndexOf(UserNameLVI) <> -1 Then
                        MainForm.DelUser(UserNameIndex)
                    End If

                    If UserName = Settings.UserName Then
                        MainForm.UserBox.Items.Clear()
                        QueueMessage("", "Kicked from the Channel.", "Error")
                        QueueMessage("", "/join The Void", "Normal Outgoing")
                    End If
                    UpdateChannelLabel()
                Case 1004
                    'Whisper to me
                    Dim UserNameTemp As String() = Message.Split(" ")
                    Dim First As Integer = Message.IndexOf(Chr(34))
                    Dim Last As Integer = Message.LastIndexOf(Chr(34))
                    Dim Difference As Integer = Last - First

                    Dim UserName As String = UserNameTemp(2)
                    Dim Text As String = Message.Substring(First + 1, Difference - 1)

                    QueueMessage("From: " + UserName, Text, "Whisper Incoming")
                    WhisperedLast = UserName
                Case 1005
                    'Channel Chat
                    Dim UserNameTemp As String() = Message.Split(" ")
                    Dim First As Integer = Message.IndexOf(Chr(34))
                    Dim Last As Integer = Message.LastIndexOf(Chr(34))
                    Dim Difference As Integer = Last - First

                    Dim UserName As String = UserNameTemp(2)
                    Dim Text As String = Message.Substring(First + 1, Difference - 1)
                    Dim RankInt As Integer = Integer.Parse(UserNameTemp(3), Globalization.NumberStyles.Any)
                    Dim Peon As Integer = "0000"
                    Select Case RankInt
                        Case "0001"
                            QueueMessage(UserName, Text, "Admin Incoming")
                        Case "0008"
                            QueueMessage(UserName, Text, "Admin Incoming")
                        Case Else
                            QueueMessage(UserName, Text, "Normal Incoming")
                    End Select
                Case 1006
                    'Announcement
                    Dim First As Integer = Message.IndexOf(Chr(34))
                    Dim Last As Integer = Message.LastIndexOf(Chr(34))
                    Dim Difference As Integer = Last - First

                    Dim Text As String = Message.Substring(First + 1, Difference - 1)
                    QueueMessage("", Text, "Info")
                Case 1007
                    'Channel Joined
                    Dim First As Integer = Message.IndexOf(Chr(34))
                    Dim Last As Integer = Message.LastIndexOf(Chr(34))
                    Dim Difference As Integer = Last - First

                    Dim Text As String = Message.Substring(First + 1, Difference - 1)
                    QueueMessage("", "Joined Channel " + Text, "System")
                    Settings.CurrentChannel = Text
                    UpdateChannelLabel()
                Case 1009
                    'Permissions
                    Dim UserNameTemp As String() = Message.Split(" ")
                    Dim UserName As String = UserNameTemp(2)
                    Dim UserNameLVI As ListViewItem = MainForm.UserBox.FindItemWithText(UserName)
                    Dim RankTag As String = UserNameLVI.Tag
                    Dim UserNameIndex As Integer = MainForm.UserBox.Items.IndexOf(UserNameLVI)
                    If MainForm.UserBox.Items.IndexOf(UserNameLVI) <> -1 Then
                        MainForm.DelUser(UserNameIndex)
                    End If

                    If MainForm.UserBox.Items.IndexOf(UserNameLVI) = -1 Then
                        MainForm.AddUser(UserName, UserNameTemp(3), RankTag)
                    End If
                Case 1018
                    'Info
                    Dim First As Integer = Message.IndexOf(Chr(34))
                    Dim Last As Integer = Message.LastIndexOf(Chr(34))
                    Dim Difference As Integer = Last - First

                    Dim Text As String = Message.Substring(First + 1, Difference - 1)
                    QueueMessage("", Text, "Info")
                Case 1019
                    'Error
                    Dim First As Integer = Message.IndexOf(Chr(34))
                    Dim Last As Integer = Message.LastIndexOf(Chr(34))
                    Dim Difference As Integer = Last - First

                    Dim Text As String = Message.Substring(First + 1, Difference - 1)
                    'TextFiltering(Text)
                    QueueMessage("", Text, "Error")
                Case 1023
                    'Emote Message
                    Dim UserNameTemp As String() = Message.Split(" ")
                    Dim First As Integer = Message.IndexOf(Chr(34))
                    Dim Last As Integer = Message.LastIndexOf(Chr(34))
                    Dim Difference As Integer = Last - First

                    Dim UserName As String = UserNameTemp(2)
                    Dim Text As String = Message.Substring(First + 1, Difference - 1)
                    Dim Emote As String = UserName + " " + Text
                    QueueMessage("", Emote, "Emote Incoming")
                Case 2000
                    QueueMessage("", "Anti-Idle Message Received from PvPGN", "Error")
                Case 2010
                    MainForm.Text = Settings.MainFormText + " <<>> Logged on As " + Settings.UserName
                    QueueMessage("", "Logged On As " & Settings.UserName, "System")
                    QueueMessage("", "/join " + Settings.DefaultChannel, "Normal Outgoing")
                    MainForm.LoginLogoutBut.Text = "Logout"
                Case Else
                    'DO NOTHING
            End Select
        Catch ex As Exception
            Console.WriteLine("SELECT TYPE FUNCTION ERROR: " + ErrorToString())
        End Try
    End Sub

    'MessageOutputHandling
    Public Shared Sub QueueMessage(ByVal UserName As String, ByVal Text As String, ByVal Type As String, Optional ByVal WriteToServer As Boolean = False)
        Try
            Select Case Type
                Case "Command"
                    OutputText("Command: " + Text, Drawing.Color.FromName(Skin.SystemColor), WriteToServer)

                    If Text.Length > 2 Then
                        Dim WhisperOutCheck() As String = Text.Split(" ", 3, StringSplitOptions.None)
                        If WhisperOutCheck(0) = "/w" Or WhisperOutCheck(0) = "/whisper" Then
                            If WhisperOutCheck.Length() >= 3 Then
                                QueueMessage("To: " + WhisperOutCheck(1), WhisperOutCheck(2), "Whisper Outgoing")
                            End If
                        End If

                        Dim ReplyOutCheck() As String = Text.Split(" ", 2, StringSplitOptions.None)
                        If ReplyOutCheck(0) = "/r" Or ReplyOutCheck(0) = "/reply" Then
                            If WhisperOutCheck.Length() >= 2 Then
                                Text = Text.Replace("/r ", "")
                                Text = Text.Replace("/reply ", "")
                                QueueMessage("To: " + WhisperedLast, Text, "Whisper Outgoing")
                            End If
                        End If

                        If Text = "Connection closed by admin." Then
                            BNetworking.ConnectionClosed()
                            QueueMessage("", "Connection Closed by Admin.", "Error")
                        End If

                        If Text = "Login failed." Then
                            BNetworking.ConnectionClosed()
                            QueueMessage("", "Login Failed. Account in use or username/password incorrect.", "Error")
                        End If
                    End If

                    If Text.Length > 4 Then
                        If Text.Substring(0, 5) = "/join" Then
                            Dim JoinCheck() As String = Text.Split(" ", 2, StringSplitOptions.None)
                            If JoinCheck.Length = 2 Then
                                If JoinCheck(1).ToLower <> Settings.CurrentChannel.ToLower Then
                                    MainForm.UserBox.Items.Clear()
                                End If
                            End If
                        End If

                        If Text.Substring(0, 5) = "/exit" Then
                            BNetworking.ConnectionClosed()
                            QueueMessage("", "Disconnected From Server.", "System")
                        End If

                        If Text.Substring(0, 5) = "/quit" Then
                            BNetworking.ConnectionClosed()
                            QueueMessage("", "Disconnected From Server.", "System")
                        End If
                    End If

                    If Text.Length > 6 Then
                        If Text.Substring(0, 7) = "/rejoin" Then
                            MainForm.UserBox.Items.Clear()
                        End If

                        If Text.Substring(0, 7) = "/logout" Then
                            BNetworking.ConnectionClosed()
                            QueueMessage("", "Disconnected From Server.", "System")
                        End If
                    End If
                Case "System"
                    OutputText(Text, Drawing.Color.FromName(Skin.SystemColor), WriteToServer)
                Case "Error"
                    OutputText(Text, Drawing.Color.FromName(Skin.ErrorColor), WriteToServer)
                Case "Info"
                    OutputText(Text, Drawing.Color.FromName(Skin.InfoColor), WriteToServer)
                Case "Whisper Incoming"
                    OutputText(UserName, Text, Drawing.Color.FromName(Skin.IncomingUserNameColor), Drawing.Color.FromName(Skin.WhisperColor), WriteToServer)
                    Commands(UserName, Text)
                Case "Normal Incoming"
                    OutputText(UserName, Text, Drawing.Color.FromName(Skin.IncomingUserNameColor), Drawing.Color.FromName(Skin.IncomingNormalTextColor), WriteToServer)
                    Commands(UserName, Text)
                Case "Admin Incoming"
                    OutputText(UserName, Text, Drawing.Color.FromName(Skin.IncomingUserNameColor), Drawing.Color.FromName(Skin.IncomingAdminTextColor), WriteToServer)
                    Commands(UserName, Text)
                Case "Emote Incoming"
                    OutputText(Text, Drawing.Color.FromName(Skin.EmoteColor), WriteToServer)
                Case "Normal Outgoing"
                    If Text.Length > 0 Then
                        If Text.Substring(0, 1) = "/" Then
                            If Text.Substring(0, Settings.Trigger.Length + 1) = "/" + Settings.Trigger Then
                                Commands(Settings.UserName, Text.Substring(Settings.Trigger.Length, Text.Length - Settings.Trigger.Length))
                            Else
                                QueueMessage("", Text, "Command")
                                SendChat(Text)
                            End If
                        Else
                            OutputText(Settings.UserName, Text, Drawing.Color.FromName(Skin.OutgoingUserNameColor), Drawing.Color.FromName(Skin.OutgoingNormalTextColor), WriteToServer)
                            Commands(Settings.UserName, Text)
                        End If
                    Else
                        OutputText(Settings.UserName, Text, Drawing.Color.FromName(Skin.OutgoingUserNameColor), Drawing.Color.FromName(Skin.OutgoingNormalTextColor), WriteToServer)
                    End If
                Case "Whisper Outgoing"
                    OutputText(UserName, Text, Drawing.Color.FromName(Skin.IncomingUserNameColor), Drawing.Color.FromName(Skin.WhisperColor), WriteToServer)
                Case "Command Outgoing"
                    If Text.Length > 0 Then
                        If Text.Substring(0, 1) = "/" Then
                            QueueMessage("", Text, "Command")
                            SendChat(Text)
                        Else
                            OutputText(Settings.UserName, Text, Drawing.Color.FromName(Skin.OutgoingUserNameColor), Drawing.Color.FromName(Skin.OutgoingNormalTextColor), WriteToServer)
                        End If
                    Else
                        OutputText(Settings.UserName, Text, Drawing.Color.FromName(Skin.OutgoingUserNameColor), Drawing.Color.FromName(Skin.OutgoingNormalTextColor), WriteToServer)
                    End If
                Case Else
                    QueueMessage("", "Unhandled or Wrong Message Type. Message: '" & Text & "' of set type '" & Type & "'", "Error")
            End Select
        Catch ex As Exception
            Console.WriteLine("QUEUE MESSAGE FUNCTION ERROR: " + ErrorToString())
        End Try
    End Sub

    Public Shared Sub SendChat(ByVal Text)
        Try
            Dim WriteMessager As BNetworking = New BNetworking()
            WriteMessager.WriteMessage(Text)
        Catch ex As Exception
            Console.WriteLine("SEND CHAT FUNCTION ERROR: " + ErrorToString())
        End Try
    End Sub

    Public Shared Function AdminAccess(ByVal User As String)
        Try
            Dim Result As Integer
            If File.Exists("admins.txt") Then
                Dim sr As StreamReader = File.OpenText("admins.txt")
                While sr.EndOfStream = False
                    If User = sr.ReadLine Then
                        sr.Close()
                        Return 1
                    Else
                        Result = 0
                    End If
                End While
                sr.Close()
            Else
                QueueMessage("", "Admin File does not exist. Creating admins.txt now.", "System")
                File.Create("admins.txt")
                'TextFormatting.ErrorMessage("Admin File does not exist. Creating admins.txt now.")
                Dim sw As New StreamWriter("admins.txt")
                sw.WriteLine("############################################################")
                sw.WriteLine("# List the Admins that have access to the bot in this file #")
                sw.WriteLine("############################################################")
                sw.Close()
                Result = 0
            End If

            If Result = 0 Then
                Return 0
                QueueMessage("", "/w " + User + "You Don't Have Enough Access to Perform that Command.", "Normal Outgoing", True)
            ElseIf Result = 1 Then
                Return 1
            Else
                QueueMessage("", "Unknown Error Occured. RUN FOR YOUR LIVES!!!", "Normal Outgoing", True)
            End If
        Catch ex As Exception
            Console.WriteLine("ADMIN CHECK FUNCTION ERROR: " + ErrorToString())
        End Try
    End Function
    '########################
    '# ADMIN COMMANDS       #
    '########################
    Public Shared Sub Commands(ByVal User As String, ByVal Message As String)
        Try
            Dim Command As String
            Dim Payload As String
            Dim SubStr As String
            'check to see what trigger was used
            If Message.Length >= Settings.Trigger.Length() Then
                SubStr = Message.Substring(0, Settings.Trigger.Length())
            Else
                SubStr = ""
            End If
            Dim Splitted As String() = Message.Split(" ")
            Command = Splitted(0).Substring(Settings.Trigger.Length(), Splitted(0).Length - Settings.Trigger.Length())
            Dim Temp As String() = Message.Split(" ", 2, StringSplitOptions.None)
            If Temp.Length > 1 Then
                Payload = Temp(1)
            End If
            If Message.Substring(0, 1) = "?" Then
                If Message.Length >= 8 Then
                    If Message.Substring(1, 7) = "trigger" Then
                        QueueMessage("", "The Trigger is: " & Settings.Trigger, "Command Outgoing", True)
                    End If
                End If
            End If

            If SubStr = Settings.Trigger And AdminAccess(User) = 1 Or SubStr = Settings.Trigger And User = Settings.UserName Then
                '!addadmin
                If Command = "addadmin" Then
                    Dim MyCrLF As String = ChrW(13) + ChrW(10)
                    If File.Exists("admins.txt") Then
                        Dim sw As New StreamWriter("admins.txt", True)
                        sw.Write(MyCrLF & Payload)
                        sw.Close()
                        QueueMessage("", "Succeeded in adding user: " & Payload & " to the admin list.", "Normal Outgoing", True)
                    Else
                        QueueMessage("", "Failed in adding user: " & Payload & " to the admin list.", "Normal Outgoing", True)
                    End If
                End If

                '!deladmin
                If Command = "deladmin" Then

                End If


                '!checkadmin
                If Command = "checkadmin" Then
                    Dim Result As Integer = AdminAccess(Payload)
                    If Result = 0 Then
                        QueueMessage("", "User: " & Payload & " is not an Admin.", "Normal Outgoing", True)
                    ElseIf Result = 1 Then
                        QueueMessage("", "User: " & Payload & " is an Admin.", "Normal Outgoing", True)
                    Else
                        QueueMessage("", "An error occured when the request was processed.", "Normal Outgoing", True)
                    End If
                End If

                '!say
                If Command = "say" Then
                    QueueMessage("", Payload, "Normal Outgoing", True)
                End If
                '!coltest
                If Command = "coltest" Then
                    QueueMessage("SAMPLE", "NORMAL OUTGOING MESSAGE", "Normal Outgoing", False)
                    QueueMessage("SAMPLE", "NORMAL INCOMING MESSAGE", "Normal Incoming")
                    QueueMessage("SAMPLE", "ADMIN INCOMING MESSAGE", "Admin Incoming")
                    QueueMessage("", "SAMPLE ERROR MESSAGE", "Error")
                    QueueMessage("", "SAMPLE INFO MESSAGE", "Info")
                    QueueMessage("", "SAMPLE SYSTEM MESSAGE", "System")
                    QueueMessage("SAMPLE", "WHISPER INCOMING MESSAGE", "Whisper Incoming")
                    QueueMessage("SAMPLE", "WHISPER OUTGOING MESSAGE", "Whisper Outgoing")
                    QueueMessage("", "SAMPLE EMOTE INCOMING MESSAGE", "Emote Incoming")
                    QueueMessage("", "SAMPLE INVALID MESSAGE", "Invalid RAWR")

                End If
                '!clear
                If Command = "clearbox" Then
                    MainForm.ChatRichBox.Clear()
                End If
                '!rcfg
                If Command = "rcfg" Then
                    QueueMessage("", "Settings.ini Reloaded", "Normal Outgoing", True)
                    Settings.ParseSettings()
                End If
                '!google
                If Command = "google" Then
                    Process.Start("http://www.google.com.au/search?hl=en&source=hp&q=" & Payload.Replace(" ", "+") & "&btnG=Google+Search&meta=&aq=f&oq=")
                End If
                '!exit
                If Command = "exit" Then
                    MainForm.Shutdown()
                End If
                '!skin
                If Command = "skin" Then
                    QueueMessage("", "Attempting to load skin '" & Payload & "'...", "System", True)
                    Skin.LoadSkin(Payload)
                End If
                '!skinlist
                If Command = "skinlist" Then
                    Dim CommandListArray As String() = Directory.GetFiles("skins")
                    Dim CommandListArrayLength As Integer = CommandListArray.Length()
                    Dim CurrentCommand As Integer = 0
                    Dim CommandListString As String = "Skins (separated by space): "

                    While 0 < CommandListArrayLength
                        CommandListArray(CurrentCommand) = CommandListArray(CurrentCommand).Replace("skins\", "")
                        CommandListArray(CurrentCommand) = CommandListArray(CurrentCommand).Replace(".ini", "")
                        CommandListString = CommandListString + CommandListArray(CurrentCommand) + " "
                        CurrentCommand = CurrentCommand + 1
                        CommandListArrayLength = CommandListArrayLength - 1
                    End While
                    QueueMessage("", "/w " & User & " " & CommandListString, "Normal Outgoing", True)
                End If

                If Command = "shout" Then
                    QueueMessage("", Payload.ToUpper, "Normal Outgoing", True)
                End If

                If Command = "eval" Then
                    QueueMessage("", ExecuteScript(User, Payload).ToString, "Normal Outgoing", True)
                End If

                If Command = "error" Then
                    Dim XYZ As String()
                    QueueMessage("", XYZ(5), "Normal Outgoing", True)
                End If

                If Command = "reverse" Then
                    Dim arrChar() As Char = Payload.ToCharArray()
                    Array.Reverse(arrChar)
                    Dim Reversed As String = arrChar
                    QueueMessage("", Reversed, "Normal Outgoing", True)
                End If

                If Command = "addquote" Then
                    Dim QuoteAdder As StreamWriter = New StreamWriter("quotes.txt", True)
                    QuoteAdder.Write(Chr(13) & Chr(10) & Payload)
                    QuoteAdder.Close()
                    QueueMessage("", "Quote Added", "Normal Outgoing", True)
                End If

                If Command = "quote" Then
                    Dim QuoteReader As StreamReader = New StreamReader("quotes.txt")
                    Dim Reader As String = QuoteReader.ReadToEnd()
                    Dim ReaderArray() As String = Reader.Split(Chr(13))
                    Dim ReaderCount As Integer = ReaderArray.Length()
                    Dim r As New Random(System.DateTime.Now.Millisecond)
                    If Payload = "" Then
                        Dim LineNumber As Integer = r.Next(0, ReaderCount)
                        ReaderArray(LineNumber) = ReaderArray(LineNumber).Replace(Chr(10), "")
                        ReaderArray(LineNumber) = ReaderArray(LineNumber).Replace(Chr(13), "")
                        QueueMessage("", ReaderArray(LineNumber), "Normal Outgoing", True)
                    Else
                        Dim NewArray As ArrayList = New ArrayList
                        Dim NewArrayCount As Integer
                        While ReaderCount > 0
                            'QueueMessage("", ReaderCount, "System")
                            Dim ReaderCur As String = ReaderArray(ReaderCount - 1).ToLower
                            If ReaderCur.Contains(Payload.ToLower) Then
                                'QueueMessage("", "ContainsB", "System")
                                NewArray.Add(ReaderArray(ReaderCount - 1))
                                'QueueMessage("", "ContainsA", "System")
                            End If
                            ReaderCount = ReaderCount - 1
                        End While

                        NewArrayCount = NewArray.Count()
                        'QueueMessage("", NewArrayCount, "System")
                        If NewArrayCount = 0 Then
                            'QueueMessage("", "Equals 0", "System")
                            QueueMessage("", "No Quotes contain the phrase: '" + Payload + "'", "Normal Outgoing", True)
                            Exit Sub
                        Else
                            'QueueMessage("", "Doesnt Equal 0", "System")
                            Dim LineNumber As Integer = r.Next(0, NewArrayCount)
                            NewArray(LineNumber) = NewArray(LineNumber).Replace(Chr(10), "")
                            NewArray(LineNumber) = NewArray(LineNumber).Replace(Chr(13), "")
                            QueueMessage("", NewArray(LineNumber), "Normal Outgoing", True)
                        End If
                    End If
                    QuoteReader.Close()
                End If
            End If

            '########################
            '# NON - ADMIN COMMANDS #
            '########################
            If SubStr = Settings.Trigger Then

                '!version
                If Command = "version" Then
                    QueueMessage("", Settings.Version, "Normal Outgoing", True)
                End If

                If Command = "roll" Then
                    QueueMessage("", Roll(Payload), "Normal Outgoing", True)
                End If

                If Command = "time" Then
                    Dim TimeInfo As DateTime = DateTime.Now
                    Dim Time As String = TimeInfo.ToString("T")
                    QueueMessage("", "It is " & Time & " on the local computer.", "Normal Outgoing", True)
                End If
            End If

            'Custom Command System
            If SubStr = Settings.Trigger And AdminAccess(User) = 1 Or SubStr = Settings.Trigger And User = Settings.UserName Then
                Dim Replacements As String()
                Dim ReplacementsLength As Integer
                Dim ReplacementsLengthCopy As Integer
                Dim Split As String()
                If Payload <> "" Then
                    Replacements = Payload.Split(" ")
                    ReplacementsLength = Replacements.Length()
                    ReplacementsLengthCopy = ReplacementsLength
                    Split = Payload.Split(" ", 2, StringSplitOptions.None)
                End If

                Dim TimeInfo As DateTime = DateTime.Now
                Dim Time As String = TimeInfo.ToString("t")
                'Command Execution
                Dim CommandFile As FileInfo = New FileInfo("commands\" & Command & ".txt")
                If CommandFile.Exists Then
                    Dim CommandReader As StreamReader = New StreamReader("commands\" & Command & ".txt")
                    While CommandReader.EndOfStream = False
                        Dim Line As String = CommandReader.ReadLine()
                        Line = Line.Replace("%CHANNEL%", Settings.CurrentChannel)
                        Line = Line.Replace("%TIME%", Time)
                        Line = Line.Replace("%0", User)
                        Line = Line.Replace("%A", Payload)
                        If Payload <> "" Then
                            While 0 < ReplacementsLength
                                Line = Line.Replace("%" & ReplacementsLength, Replacements(ReplacementsLength - 1))
                                ReplacementsLength = ReplacementsLength - 1
                            End While
                            ReplacementsLength = ReplacementsLengthCopy
                        End If
                        QueueMessage("", Line, "Command Outgoing", True)
                    End While
                    CommandReader.Close()
                End If
                'Command Creation
                If Command = "addcmd" Then
                    If Payload <> "" Then
                        If Split.Length = 2 Then
                            Dim FilteredCommandName As String = FilterString(Split(0))
                            Dim CommandWriter As StreamWriter = New StreamWriter("commands\" & FilteredCommandName & ".txt")
                            Split(1) = Split(1).Replace("&", Chr(10))
                            CommandWriter.Write(Split(1))
                            CommandWriter.Close()
                            QueueMessage("", "Command '" & FilteredCommandName & "' created successfully by '" & User & "'", "Normal Outgoing", True)
                        Else
                            QueueMessage("", "Incorrect syntax. Correct syntax is: '!addcmd commandname whathappens'.", "Normal Outgoing", True)
                        End If
                    End If
                End If
                'Command Deletion
                If Command = "delcmd" Then
                    Dim CommandDelFile As FileInfo = New FileInfo("commands\" & Payload & ".txt")
                    If CommandDelFile.Exists Then
                        CommandDelFile.Delete()
                        QueueMessage("", "Command '" & Payload & "' deleted by '" & User & "'", "Normal Outgoing", True)
                    Else
                        QueueMessage("", "Command '" & Payload & "' not deleted as it doesnt exist.", "Normal Outgoing", True)
                    End If
                End If

                '!cmdlist
                If Command = "cmdlist" Then
                    Dim CommandListArray As String() = Directory.GetFiles("commands")
                    Dim CommandListArrayLength As Integer = CommandListArray.Length()
                    Dim CurrentCommand As Integer = 0
                    Dim CommandListString As String = "Custom Commands (separated by space): "

                    While 0 < CommandListArrayLength
                        CommandListArray(CurrentCommand) = CommandListArray(CurrentCommand).Replace("commands\", "")
                        CommandListArray(CurrentCommand) = CommandListArray(CurrentCommand).Replace(".txt", "")
                        CommandListString = CommandListString + CommandListArray(CurrentCommand) + " "
                        CurrentCommand = CurrentCommand + 1
                        CommandListArrayLength = CommandListArrayLength - 1
                    End While
                    QueueMessage("", "/w " & User & " " & CommandListString, "Normal Outgoing", True)
                End If
            End If
        Catch ex As Exception
            Console.WriteLine("COMMAND FUNCTION ERROR: " + ErrorToString())
        End Try
    End Sub

    Private Shared Function FilterString(ByVal FilterStringV As String)
        Try
            FilterStringV = FilterStringV.Replace(Chr(32), "")
            FilterStringV = FilterStringV.Replace("!", "")
            FilterStringV = FilterStringV.Replace("@", "")
            FilterStringV = FilterStringV.Replace("#", "")
            FilterStringV = FilterStringV.Replace("$", "")
            FilterStringV = FilterStringV.Replace("%", "")
            FilterStringV = FilterStringV.Replace("^", "")
            FilterStringV = FilterStringV.Replace("*", "")
            FilterStringV = FilterStringV.Replace("&", "")
            FilterStringV = FilterStringV.Replace("(", "")
            FilterStringV = FilterStringV.Replace(")", "")
            FilterStringV = FilterStringV.Replace("\", "")
            FilterStringV = FilterStringV.Replace("/", "")
            FilterStringV = FilterStringV.Replace("?", "")
            FilterStringV = FilterStringV.Replace("<", "")
            FilterStringV = FilterStringV.Replace(">", "")
            FilterStringV = FilterStringV.Replace(".", "")
            FilterStringV = FilterStringV.Replace(",", "")
            Return FilterStringV
        Catch ex As Exception
            Console.WriteLine("FILTER STRING FUNCTION ERROR: " + ErrorToString())
        End Try
    End Function

    Public Shared Function ExecuteScript(ByVal UserExecuting As String, ByVal MessageToExecute As String)
        On Error GoTo ErrorM
        Dim Script As New MSScriptControl.ScriptControl()
        Script.Language = "VBScript"
        Script.AllowUI = True
        Return Script.Eval(MessageToExecute)
ErrorM:
        Return "EVAL ERROR. '" & MessageToExecute & "' could not be executed. REASON: '" & ErrorToString() & "'"
    End Function

    Public Shared Function Roll(ByVal MaximumS As String)
        On Error GoTo ErrorM
        Dim Minimum As Integer = 1
        Dim Maximum As Integer = Convert.ToInt64(MaximumS)
        Dim r As New Random(System.DateTime.Now.Millisecond)
        Dim RandomNumber As String = r.Next(1, Maximum).ToString()
        Return RandomNumber
ErrorM:
        Dim RollError As String = "ROLL ERROR: " & ErrorToString()
        RollError = RollError.Replace(Chr(10), "")
        RollError = RollError.Replace(Chr(13), "")
        Return RollError
    End Function

    'Formatting
    Public Shared Sub AutoScroller(ByVal Box As Object)
        Try
            Box.Select(Box.Text.Length, 0)
            Box.ScrollToCaret()
        Catch ex As Exception
            Console.WriteLine("AUTOSCROLLER FUNCTION ERROR: " + ErrorToString())
        End Try
    End Sub

    Public Shared Function GetHexColor(ByVal colorObj As System.Drawing.Color) As String
        Try
            Return "#" & Hex(colorObj.R) & Hex(colorObj.G) & Hex(colorObj.B)
        Catch ex As Exception
            Console.WriteLine("GET HEX COLOR FUNCTION ERROR: " + ErrorToString())
        End Try
    End Function

    Private Shared Sub OutputText(ByVal Text As String, ByVal TextColor As Drawing.Color, ByVal WriteToServer As Boolean)
        Try
            'gets current time
            Dim TimeInfo As DateTime = DateTime.Now
            'converts time to string
            Dim Time As String = TimeInfo.ToString("T")
            'pads time string to 11 chars
            Dim TimePad As String = Time.PadRight(11)
            'creates string to add new line
            Dim MyCrLF As String = ChrW(13) + ChrW(10)
            'adds line to textbox
            MainForm.ChatRichBox.AppendText(TimePad)
            'Colour Date
            MainForm.ChatRichBox.SelectionStart = MainForm.ChatRichBox.Find(TimePad, RichTextBoxFinds.Reverse)
            MainForm.ChatRichBox.SelectionColor = Drawing.Color.FromName(Skin.DateColor)

            MainForm.ChatRichBox.AppendText(" " & Text)
            'ColourText
            If Text.Length > 0 Then
                MainForm.ChatRichBox.SelectionStart = MainForm.ChatRichBox.Find(Text, System.Windows.Forms.RichTextBoxFinds.Reverse)
                MainForm.ChatRichBox.SelectionColor = TextColor
            End If
            MainForm.ChatRichBox.AppendText(MyCrLF)
            AutoScroller(MainForm.ChatRichBox)

            If WriteToServer = True Then
                If BNetworking.T.Connected Then
                    SendChat(Text)
                End If
            End If
            LogMessage("<font font=Calibri size=2 color=" & GetHexColor(Drawing.Color.FromName(Skin.DateColor)) & ">" + TimePad + " </font> " + " <font font=Calibri size=2 color=" & GetHexColor(TextColor) & ">&nbsp;" + Text + "</font><br>")
        Catch ex As Exception
            Console.WriteLine("OUTPUT TEXT FUNCTION ERROR: " + ErrorToString())
        End Try
    End Sub

    Private Shared Sub OutputText(ByVal User As String, ByVal Text As String, ByVal UserColor As Drawing.Color, ByVal TextColor As Drawing.Color, ByVal WriteToServer As Boolean)
        Try
            'gets current time
            Dim TimeInfo As DateTime = DateTime.Now
            'converts time to string
            Dim Time As String = TimeInfo.ToString("T")
            'pads time string to 11 chars
            Dim TimePad As String = Time.PadRight(11)
            'creates string to add new line
            Dim MyCrLF As String = ChrW(13) + ChrW(10)
            'Combined User
            Dim UpUser As String = " <" & User & "> "
            'adds line to textbox
            MainForm.ChatRichBox.AppendText(TimePad)
            'Colour Date
            MainForm.ChatRichBox.SelectionStart = MainForm.ChatRichBox.Find(TimePad, RichTextBoxFinds.Reverse)
            MainForm.ChatRichBox.SelectionColor = Drawing.Color.FromName(Skin.DateColor)
            MainForm.ChatRichBox.AppendText(UpUser)
            'Colour UserName
            MainForm.ChatRichBox.SelectionStart = MainForm.ChatRichBox.Find(UpUser, RichTextBoxFinds.Reverse)
            MainForm.ChatRichBox.SelectionColor = UserColor
            MainForm.ChatRichBox.AppendText(Text)
            'Colour Text
            If Text.Length > 0 And Text <> "" And Text <> Chr(10) Then
                MainForm.ChatRichBox.SelectionStart = MainForm.ChatRichBox.Find(Text, System.Windows.Forms.RichTextBoxFinds.Reverse)
                MainForm.ChatRichBox.SelectionColor = TextColor
            End If
            MainForm.ChatRichBox.AppendText(MyCrLF)
            AutoScroller(MainForm.ChatRichBox)

            If WriteToServer = True Then
                If BNetworking.T.Connected Then
                    SendChat(Text)
                End If
            End If
            LogMessage("<font font=Calibri size=2 color=" & GetHexColor(Drawing.Color.FromName(Skin.DateColor)) & ">" + TimePad + " </font>" + "<font font=Calibri size=2 color=" & GetHexColor(UserColor) & "> &nbsp;&lt;" + User + "&gt; </font>" + "<font font=Calibri size=2 color=" & GetHexColor(TextColor) & ">" + Text + "</font><br>")
        Catch ex As Exception
            Console.WriteLine("OUTPUT TEXT FUNCTION ERROR: " + ErrorToString())
        End Try
    End Sub

    Public Shared Sub LogMessage(ByVal Message As String, Optional ByVal WriteNow As Boolean = False)
        Try
            If Settings.LoggingStatus = "1" Then
                LogMessageQueue.Enqueue(Message)
                If LogMessageQueue.Count >= Settings.LogEveryNumberMessages Or WriteNow = True Then
                    Dim LogMessageQueueCount As Integer = LogMessageQueue.Count
                    Dim DateNow As String = DateTime.Today.ToString("dd-MM-yyyy")
                    'Dim DateNew As String = DateNow.Replace("/", "-")
                    Dim FileName As FileInfo = New FileInfo("logs\" + DateNow + ".html")
                    Dim sw As StreamWriter
                    If FileName.Exists = False Then
                        sw = New StreamWriter("logs\" + DateNow + ".html", True)
                        sw.WriteLine("<body bgcolor=#000000>")
                        sw.WriteLine("<font font=Calibri size=4 color=#FFFFFF>Log From " & DateNow & "</font><br>")
                        While LogMessageQueueCount > 0
                            sw.WriteLine(LogMessageQueue.Peek())
                            LogMessageQueue.Dequeue()
                            LogMessageQueueCount = LogMessageQueueCount - 1
                        End While
                        sw.Close()
                    Else
                        sw = New StreamWriter("logs\" + DateNow + ".html", True)
                        While LogMessageQueueCount > 0
                            sw.WriteLine(LogMessageQueue.Peek())
                            LogMessageQueue.Dequeue()
                            LogMessageQueueCount = LogMessageQueueCount - 1
                        End While
                        sw.Close()
                    End If
                End If
            End If
        Catch ex As Exception
            Console.WriteLine("LOG TEXT FUNCTION ERROR: " + ErrorToString())
        End Try
    End Sub
End Class
